package com.changyou.skynet.task.service;

import java.text.ParseException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import org.quartz.CronTrigger;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.changyou.skynet.task.domain.TSTimeTaskEntity;

@Service
public class DynamicTask {
    @Resource
    private Scheduler schedulerFactory;

    private static final Logger logger = LoggerFactory
            .getLogger(DynamicTask.class);
    // 可用的job列表
    private static Set<String> JobNameSet = new HashSet<String>();
    // 任务列表
    private static Map<String, CronTrigger> triggerMap = new HashMap<String, CronTrigger>();

    public DynamicTask() {
        super();
    }

    public static Set<String> getJobNameSet() {
        return JobNameSet;
    }

    public static void setJobNameSet(Set<String> jobNameSet) {
        JobNameSet = jobNameSet;
    }

    /**
     * 更新定时任务的触发表达式
     * 
     * @param triggerName
     *            触发器名字
     * @param start
     *            触发表达式
     * @return 成功则返回true，否则返回false
     */
    public boolean startOrStop(String taskId, boolean start) {
        try {
            CronTrigger trigger = triggerMap.get(taskId);
            // 新任务第一次运行；
            if (null == trigger) {
                // 开启或暂停已有任务。
                trigger = (CronTrigger) getTrigger(taskId,
                        Scheduler.DEFAULT_GROUP);
            }
            if (null == trigger) {
                logger.info("startOrStop error trigger is null.");
                return false;
            }
            // 设置任务状态
            if (start) {
                if (null == schedulerFactory.getTrigger(trigger.getName(),
                        trigger.getGroup())) {
                    // 初次启动任务的时候，将任务加入schedulerFactory。并清空新任务Map中的记录。
                    schedulerFactory.scheduleJob(trigger);
                    triggerMap.remove(taskId);
                } else {
                    // 重新启动已有任务
                    schedulerFactory.resumeTrigger(trigger.getName(),
                            trigger.getGroup());
                }
                logger.info("trigger the start successfully!!");
            } else {
                if (null != schedulerFactory.getTrigger(trigger.getName(),
                        trigger.getGroup())) {
                    schedulerFactory.pauseTrigger(trigger.getName(),
                            trigger.getGroup());
                    logger.info("trigger the pause successfully!!");
                }
                //初始化任务，如果不是start状态，不加入scheduler中。
            }
            return true;
        } catch (SchedulerException e) {
            logger.error("Fail to startOrStop. " + e);
            return false;
        }
    }

    /*
     * 添加一个新Trigger
     */
    public boolean addTrigger(TSTimeTaskEntity task) {
        try {
            CronTrigger trigger = new CronTrigger(task.getTaskId(),
                    Scheduler.DEFAULT_GROUP, task.getJobId(),
                    Scheduler.DEFAULT_GROUP, task.getCronExpression());
            // 将trigger保存起来
            triggerMap.put(trigger.getName(), trigger);
            return true;
        } catch (ParseException e1) {
            e1.printStackTrace();

        }
        return false;
    }

    // 删除一个Trigger
    public boolean deleteJobTrigger(TSTimeTaskEntity task) {
        Trigger trigger = getTrigger(task.getTaskId(), Scheduler.DEFAULT_GROUP);
        if (trigger != null) {
            try {
                return schedulerFactory.unscheduleJob(trigger.getName(),
                        Scheduler.DEFAULT_GROUP);
            } catch (SchedulerException e) {
                e.printStackTrace();
            }
        }
        // 如果查找不到，返回成功
        return true;
    }

    // 获取Trigger
    private Trigger getTrigger(String triggerName, String groupName) {
        Trigger trigger = null;
        try {
            trigger = schedulerFactory.getTrigger(triggerName, groupName);
        } catch (SchedulerException e) {
            logger.warn("Fail to get the trigger (triggerName: " + triggerName
                    + ", groupName : " + groupName + ")");
            return null;
        }
        if (trigger == null) {
            logger.warn("Can not found the trigger of triggerName: "
                    + triggerName + ", groupName : " + groupName);
        }
        return trigger;
    }

    // 添加一个job
    public void addValidJob() {
        try {
            JobNameSet.add("SayHiService");
            JobDetail job;
            job = new JobDetail("SayHiService", Scheduler.DEFAULT_GROUP,
                    SayHiService.class);
            schedulerFactory.addJob(job, true);
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }

    // 测试添加一个任务
    public void addTestJob() {
        try {
            JobDetail job = new JobDetail("job1", Scheduler.DEFAULT_GROUP,
                    SayHiService.class);
            CronTrigger trigger = new CronTrigger("trigger1",
                    Scheduler.DEFAULT_GROUP, "job1", Scheduler.DEFAULT_GROUP,
                    "0/5 * * * * ?");
            schedulerFactory.scheduleJob(job, trigger);
        } catch (ParseException e1) {
            e1.printStackTrace();

        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }
}
